delete(s); clear;
global h dataBuffer maxPoints;
h = animatedline; % 创建实时绘图对象
ax = gca;
ax.YLim = [0, 255]; % 根据数据范围设置 Y 轴范围
grid on;

% 初始化变量
dataBuffer = [];
maxPoints = 100;

% 打开串口
port = "COM10"; % 替换为实际串口号
baudRate = 115200; % 替换为实际波特率
s = serialport(port, baudRate); % 打开串口

% 配置串口回调函数
disp('接收数据中...');
byteCount = 10; % 每次接收 10 个字节触发回调
configureCallback(s, "byte", byteCount, @serialCallback);

% 蓝牙连接部分
disp('Scanning for BLE devices...');
devices = blelist;
disp(devices);

deviceName = 'QWER'; % 替换为 STM32WB55 名称
disp(['Connecting to ', deviceName, '...']);
b = ble(deviceName);
disp(['Connected to ', deviceName]);

serviceUUID = '0000FE40-CC7A-482A-984A-7F2ED5B3E58F';
characteristicUUID = '0000FE41-8E22-4541-9D4C-21EDAE82ED19';
characteristic = characteristic(b, serviceUUID, characteristicUUID);

Fs = 100;
t = 0:1/Fs:2*pi;
amplitude = 120;
offset = 121;
sineWave = uint8(amplitude * sin(t) + offset);

disp('持续发送数据到 STM32WB55');
sendBluetoothData(characteristic, sineWave);

function sendBluetoothData(characteristic, sineWave)
    while true
        for i = 1:length(sineWave)
            write(characteristic, sineWave(i));
            pause(0.05);
        end
    end
end
function serialCallback(src, ~)
    global h dataBuffer maxPoints;

    try
        % 读取串口数据
        if src.NumBytesAvailable > 0
            data = read(src, src.NumBytesAvailable, "uint8"); % 读取字节数据

            % 获取当前时间，以秒为单位
            currentTime = posixtime(datetime('now')); % 当前时间戳（以秒为单位）

            % 更新实时绘图
            for i = 1:length(data)
                addpoints(h, currentTime, data(i)); % 添加数据点
            end

            % 更新绘图轴范围
            startTime = currentTime - 10; % 显示最近 10 秒数据
            endTime = currentTime;

            % 确保 XLim 范围合法
            if startTime < endTime
                ax = gca;
                ax.XLim = [startTime, endTime];
                drawnow;
            end

            % 更新数据缓冲区
            dataBuffer = [dataBuffer; data];
            if length(dataBuffer) > maxPoints
                dataBuffer = dataBuffer(end - maxPoints + 1:end);
            end
        end
    catch ME
        disp(['回调中的错误: ', ME.message]);
    end
end
